package kontrolno2;

import java.security.InvalidParameterException;
import java.util.Scanner;

import javax.mail.MessagingException;

public class CardNumbersUI {
	CardNumbers numbers = new CardNumbers();

	public CardNumbersUI() {
		super();
		this.numbers = new CardNumbers();
	}

	public static void startCardNumbers() {
		CardNumbersUI start = new CardNumbersUI();
		start.start();
	}

	private void start() {
		System.out.println("Choose an action:");
		System.out.println("1. Add a number.");
		System.out.println("2. Get the most common number.");
		System.out.println("3. Remove repeating numbers and sort the list.");
		System.out.println("4. Send the list of numbers to an email address");
		System.out.println("5. Exit");
		int choice = readInt(1, 5);
		switch (choice) {
			case 1: addNumber(); break;
			case 2: getMostCommonNumber(); break;
			case 3: trimAndSort(); break;
			case 4: email(); break;
			case 5: exit(); break;
		}
	}
	
	private void addNumber() {
		System.out.println("Enter a number to add:");
		String number = readLine();
		try {
			numbers.addCardNumbers(number);
			start();
		} catch (ArrayStoreException e) {
			System.out.println(e.getMessage());
			start();
		} catch (InvalidParameterException e) {
			System.out.println(e.getMessage());
			addNumber();
		}
	}
	
	private void getMostCommonNumber() {
		System.out.println("The most common number is " + numbers.getMostCommonNumber());
		start();
	}
	
	private void trimAndSort() {
		numbers.trim();
		numbers.sort();
		start();
	}
	
	private void email () {
		System.out.println("Enter an email address:");
		String email = readLine();
		try {
			numbers.email(email);
			start();
		} catch (MessagingException e) {
			e.getCause().printStackTrace();
			System.out.println(e.getMessage());
			email();
		}
	}
	
	private void exit() {
		System.out.println("Thank you for using our software. Goodbye.");
	}

	private int readInt(int min, int max) {
		Scanner sc = new Scanner(System.in);
		try {
			int value = sc.nextInt();
			if (value<min||value>max) throw new Exception();
			return value;
		} catch (Exception e) {
			System.out.println("Invalid entry, choose again.");
			return readInt(min, max);
		}
	}
	
	private String readLine() {
		Scanner sc = new Scanner(System.in);
		return sc.nextLine();
	}
}
